import { Table, Form, Button, Row, Col, Input, Select, DatePicker, Modal } from "antd";
const { RangePicker } = DatePicker;
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { MainContent } from "src/business/components/style-components/main-content";
// import { InputType } from "src/business/components/buss-components/sign-frame-layout";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
// import { request } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { ModalSearch } from "src/business/components/buss-components/modal-search";
import RadioGroup from "antd/lib/radio/group";

// import { table_param } from "src/projects/app/util-tool";
// import { ROUTE_PATH } from "src/projects/router";
import { request_func } from "src/business/util_tool";
let moment = require('moment');

// const Option = Select.Option;
/**
 * 组件：费用结算状态
 */
export interface costAccountingViewState extends ReactViewState {
    select_date?: any;
    /** 接口名 */
    request_url?: string;
    base_data?: any;
    pagination?: any;
    loading?: any;
    condition?: any;
    visible?: boolean;
}

/**
 * 组件：费用结算
 */

export enum InputType { "upload", "input", "select", "preText", "customProperties", "date", "rangePicker", "radioGroup", "modal_search" }

const render_jsx = {
    upload: (option: any) => <FileUploadBtn list_type={"picture-card"} contents={"plus"} {...option} />,
    input: (option: any) => <Input height="small" radius='inputDefault' {...option} />,
    select: (option: any) => <Select {...option}  >{option.childrens}</Select>,
    // customProperties: (option: any) => <CustomProperties {...option} />,
    date: (option: any) => <DatePicker format={"YYYY-MM-DD"} {...option} />,
    rangePicker: (option: any) => <RangePicker  {...option} />,
    radioGroup: (option: any) => <RadioGroup {...option} />,
    modal_search: (option: any) => <ModalSearch {...option} />,
};
export class costAccountingView extends ReactView<costAccountingViewControl, costAccountingViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            select_date: moment().format("YYYY-MM") + '-01',
            base_data: [],
            pagination: {},
            loading: false,
            condition: {},
            visible: false,
        };
    }

    componentDidMount() {
        this.setState({ condition: { state: 'new' } });
        this.request_order({ state: 'new' }, 1);
    }
    handleTableChange = (pagination: any, filters: any, sorter: any) => {
        const pager = { ...this.state.pagination };
        pager.current = pagination.current;
        this.setState({
            pagination: pager,
        });
        // this.request_order(this.state.condition, pagination.current);

    }
    request_order = (condition: any, page: any) => {
        request_func(this, AppServiceUtility.cost_accounting_service[this.props.request_url], [condition], (data: any) => {
            const pagination = { ...this.state.pagination };
            pagination.total = data.total;
            this.setState({ base_data: data.result, pagination });
        });
    }
    /** 发送服务记录 */
    sendRecode = () => {
        const base_data: any = this.state.base_data;
        let recode_ids = [];
        for (var i = 0; i < base_data.length; i++) {
            for (var x = 0; x < base_data[i].recode.length; x++) {
                recode_ids.push(base_data[i].recode[x].id);
            }

        }
        request_func(this, AppServiceUtility.cost_accounting_service.cost_account_manage, [recode_ids], (data: any) => {
            alert(data === 'Success' ? '发送成功' : '发送失败');
            // const condition = { 'cost_status': '未发送' };
            // this.setState({ condition });
            this.request_order({}, 1);
        });
    }
    reset() { }
    // 核算
    cost_func = () => {
        this.setState({ visible: false });
        request_func(this, AppServiceUtility.accommodation_process_service.auto_creat_service_record_manage, [], (data: any) => {
            alert(data === 'Success' ? '核算成功' : '核算失败');
            this.request_order({}, 1);
        });
    }

    handleSearch = (e: any) => {
        e.preventDefault();
        let { props } = this;
        props.form!.validateFields((err: any, values: any) => {
            // this.setState({ condition: values });
            console.info('hello world', values);
            this.request_order(values, 1);
        });
    }
    formatMonth = (s: any) => {
        return s < 10 ? '0' + s : s;
    }
    render() {
        // const status = ['已发送', '未发送', '发送失败'];
        // const status_list = status.map((val: any) => {
        //     return (<Option key={val}>{val}</Option>);
        // });
        let json_info = {
            type_show: false,
            edit_form_items_props: [
                {
                    type: InputType.input,
                    label: "长者姓名",
                    decorator_id: "name",
                    option: {
                        placeholder: '请输入长者姓名'
                    }
                },
                // {
                //     type: InputType.date,
                //     label: "订单开始时间",
                //     decorator_id: "start_date",
                //     option: {
                //         placeholder: '请选择时间',
                //         // onChange: (e: any) => {
                //         //     const select_date = moment(e).format('YYYY-MM-dd') + '-01';
                //         //     this.setState({ select_date });
                //         // }
                //     }
                // },
                // {
                //     type: InputType.date,
                //     label: "订单结束时间",
                //     decorator_id: "end_date",
                //     option: {
                //         placeholder: '请选择时间',
                //         // onChange: (e: any) => {
                //         //     const select_date = moment(e).format('YYYY-MM') + '-01';
                //         //     this.setState({ select_date });
                //         // }
                //     }
                // }
            ],
            btn_props: [
                {
                    label: '核算',
                    btn_method: () => {
                        this.setState({ visible: true });
                    },
                    icon: 'plus'
                },
                {
                    label: '发送',
                    btn_method: this.sendRecode,
                    icon: 'plus'
                }

            ],
            // on_row_selection: this.on_row_selection,
            service_object: AppServiceUtility.cost_accounting_service,
            service_option: {
                select: {
                    service_func: 'get_cost_account_list_all',
                    service_condition: [{}]
                }
            }
        };

        const expandedRowRender = (item: any) => {
            const base_data: any = this.state.base_data;
            const columns = [
                { title: '服务项目', dataIndex: 'item_name', key: 'item_name' },
                { title: '金额', dataIndex: 'cost', key: 'cost' },
                { title: '开始时间', dataIndex: 'start_date', key: 'start_date' },
                { title: '结束时间', dataIndex: 'end_date', key: 'end_date' }
            ];

            const data_recode: any = [];
            for (var i = 0; i < base_data.length; i++) {
                if (item.id === base_data[i].order_id) {
                    for (var x = 0; x < base_data[i].recode.length; x++) {
                        data_recode.push({
                            key: x,
                            item_name: base_data[i].recode[x].name,
                            cost: base_data[i].recode[x].valuation_amount,
                            start_date: base_data[i].recode[x].start_date,
                            end_date: base_data[i].recode[x].end_date
                        });
                    }
                }

            }
            return <Table columns={columns} dataSource={data_recode} pagination={false} />;
        };
        const columns = [
            { title: '订单编号', dataIndex: 'id', key: 'id' },
            { title: '长者', dataIndex: 'name', key: 'name' },
            // { title: '居住情况', dataIndex: 'state', key: 'state' },
            { title: '床位', dataIndex: 'bed_name', key: 'bed_name' },
            { title: '证件号码', dataIndex: 'id_card', key: 'id_card' },
        ];

        const data = [];
        const base_data = this.state.base_data;
        // 父级title数据
        for (let i = 0; i < base_data.length; ++i) {
            // 获取当前页面的所有订单id
            data!.push({
                key: i,
                id: base_data[i].order_id,
                name: base_data[i].user.name,
                bed_name: base_data[i].bed![0] ? base_data[i].bed[0].name : '',
                id_card: base_data[i].user.id_card,
                // state: base_data[i].check.state,
            });
        }
        const { getFieldDecorator } = this.props.form!;
        return (
            <MainContent>
                <div className='form-bottom'>
                    <Form
                        className="nt-sign-manage-layout"
                        onSubmit={this.handleSearch}
                    >
                        <Row gutter={24}>
                            {
                                json_info.edit_form_items_props ? json_info.edit_form_items_props.map((e, i) =>
                                    (
                                        <Col span={8} key={i}>
                                            <Form.Item
                                                label={e.label}
                                            >
                                                {getFieldDecorator(e.decorator_id, {
                                                    /** 日期特殊处理 暂不需要初始化当天日期 */
                                                    initialValue: '', // e.type === InputType.date ? moment(e.default_value) : e.default_value,
                                                })(
                                                    render_jsx[InputType[e.type]](e.option)
                                                )}
                                            </Form.Item>
                                        </Col>
                                    )
                                )
                                    :
                                    null
                            }
                            <Col span={24}>
                                <Row type="flex" style={{ flexDirection: "row-reverse" }}>
                                    <Button type='ghost' htmlType='button' onClick={this.reset} >重置</Button>
                                    <Button htmlType="submit" type='primary' className='res-btn'>查询</Button>
                                </Row>
                            </Col>
                        </Row >
                        <Row type="flex" >
                            {
                                json_info.btn_props ?
                                    json_info.btn_props !== undefined && json_info.btn_props.map((item, idx) => {
                                        return <Button type='primary' onClick={item.btn_method} key={idx} icon={item.icon!} style={{ marginLeft: '10px' }}>{item.label}</Button>;
                                    }) : <span />

                            }
                        </Row>
                    </Form>
                    <Modal
                        title="核算"
                        visible={this.state.visible}
                        onOk={this.cost_func}
                        okText='确定'
                        cancelText='取消'
                        onCancel={() => { this.setState({ visible: false }); }}
                    >
                        <p>将要对所有长者进行核算?</p>
                    </Modal>
                </div>
                <Table
                    className="components-table-demo-nested"
                    columns={columns}
                    rowKey='id'
                    expandedRowRender={expandedRowRender}
                    dataSource={data}
                    pagination={this.state.pagination}
                    onChange={this.handleTableChange}
                /></MainContent>

        );
    }
}

/**
 * 控件：费用结算
 * 描述
 */
@addon('costAccountingView', '费用结算', '描述')
@reactControl(Form.create<any>()(costAccountingView), true)
export class costAccountingViewControl extends ReactViewControl {
    /** 请求接口名 */
    public request_url: string;
    /** 获取权限接口类 */
    public permission_class?: any;
    /** 获取权限接口方法名 */
    public get_permission_name?: string;
    /** 查询权限 */
    public select_permission?: string;
    /** 编辑权限 */
    public edit_permission?: string;
    /** 删除权限 */
    public delete_permission?: string;
    /** 新增权限 */
    public add_permission?: string;
}